<template>
  <div class="card bg-white rounded-xl shadow-sm p-6 mb-6">
    <!-- 原有问候语和日期信息 -->
    <div class="text-gray-800" style="font-size: 3em; font-weight: bold">
      {{ greeting }}，{{ data.user.name || '' }}
      <el-button style="margin-left: 50px;margin-bottom: 10px" v-if="data.user.role === 'ADMIN'" @click="data.showDialog = true" type="info">
        数据导入帮助
      </el-button>
    </div>
    <div class="text-gray-600 mt-2" style="font-size: 2em; font-weight: bold">
      今天是 {{ currentDate }}，<span style="color:#7e55fc;">{{ termWeekInfo }}</span>
    </div>
    <!-- 积分对比柱状图 -->
    <!-- 增加明确的尺寸样式 -->
    <div class="mt-8 chart-container">
      <h3 class="text-lg font-medium text-gray-700 mb-3">
        {{ data.examOptions[0]?.examName || '考试积分' }}-各班级积分对比
      </h3>
      <div ref="chartRef" class="chart-wrapper"></div>
    </div>
  </div>

  <!-- 导入指南对话框 -->
  <el-dialog
      v-model="data.showDialog"
      title="注意事项"
      width="500"
      destroy-on-close
      center
  >
  <div class="p-6">
    <p class="text-gray-600 mb-4">请按照以下格式导入成绩数据，确保表头正确且数据完整：</p>
    <div class="flex flex-col gap-6 mt-4">
      <div>
        <h3 class="font-medium text-gray-700 mb-2">Excel表头示例（数据不能为空）</h3>
        <img src="@/assets/imgs/geshi.png" alt="Excel格式示例"
             class="max-w-full h-auto border border-gray-200 rounded-md shadow-sm">
      </div>
      <div class="bg-blue-50 p-4 rounded-md border border-blue-100">
        <h3 class="font-medium text-blue-800 mb-2 flex items-center">
          <i class="fa fa-info-circle mr-2"></i>导入注意事项
        </h3>
        <ul class="list-disc list-inside text-blue-700 space-y-1 text-sm">
          <li>确保所有单元格格式为文本或数字，避免特殊格式</li>
          <li>成绩字段请填写数字，范围0-120</li>
        </ul>
      </div>
    </div>
  </div>

  </el-dialog>
</template>

<script setup>
import {reactive, computed, onMounted, ref, watch, onUnmounted, nextTick} from "vue";
import {ElLoading, ElMessage} from "element-plus";
import request from "@/utils/request.js";
import * as echarts from "echarts";

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"),
  showDialog: false,
  selectedExam: null,
  examOptions: [],
  tableData: []
});

// 图表相关
const chartRef = ref(null);
let chartInstance = null;

onMounted(async () => {
  await fetchExams();
  if (data.examOptions.length > 0) {
    load();
  }
});

// 关键修复：使用nextTick确保DOM渲染完成后再初始化图表
const initChart = () => {
  // 先销毁已有实例
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 使用nextTick确保DOM已渲染
  nextTick(() => {
    if (chartRef.value) {
      // 检查容器尺寸
      const clientWidth = chartRef.value.clientWidth;
      const clientHeight = chartRef.value.clientHeight;

      if (clientWidth === 0 || clientHeight === 0) {
        console.warn('图表容器尺寸为0，尝试设置默认尺寸');
        // 强制设置尺寸
        chartRef.value.style.width = '100%';
        chartRef.value.style.height = '400px';
      }

      // 初始化图表
      chartInstance = echarts.init(chartRef.value);
      chartInstance.setOption(barChartOption.value);

      // 监听窗口大小变化
      window.addEventListener('resize', handleResize);
    }
  });
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 监听数据变化
watch(
    () => data.tableData,
    () => {
      if (data.tableData.length > 0) {
        initChart();
      }
    }
);

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});

// 获取考试列表
const fetchExams = () => {
  return request.get('/exams/getExams').then(res => {
    if (res.code === '200') {
      data.examOptions = res.data
          .slice()
          .sort((a, b) => new Date(b.examTime) - new Date(a.examTime));
      if (data.examOptions.length > 0 && data.selectedExam === null) {
        data.selectedExam = data.examOptions[0].examId;
      }
    } else {
      ElMessage.error(res.msg || '加载考试列表失败');
    }
  });
};

// 加载班级数据
const load = () => {
  if (!data.selectedExam) {
    ElMessage.error('请先选择考试!');
    return false;
  }
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  request.get('/fenxi/getAll', {
    params: {selectedExam: data.selectedExam}
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data;
    } else {
      ElMessage.error(res.msg || '加载失败');
    }
  }).catch(err => {
    console.error('加载失败:', err);
    ElMessage.error('加载数据时发生错误');
  }).finally(() => {
    loading.close();
  });
};

// 动态问候语
const greeting = computed(() => {
  const hour = new Date().getHours();
  if (hour < 12) return '早上好';
  if (hour < 18) return '下午好';
  return '晚上好';
});

// 格式化当前日期
const currentDate = computed(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}年${month}月${day}日`;
});

// 计算学期周次
const termWeekInfo = computed(() => {
  const current = new Date();
  const preTermStart = new Date('2025-08-25');
  const termFirstWeekStart = new Date('2025-09-01');
  const getDaysDiff = (target) => Math.floor((current - target) / (24 * 60 * 60 * 1000));
  const daysFromPreTerm = getDaysDiff(preTermStart);
  const daysFromFirstWeek = getDaysDiff(termFirstWeekStart);

  if (current < preTermStart) return '学期未开始';
  if (current < termFirstWeekStart) return '学前周';
  const weekNum = Math.floor(daysFromFirstWeek / 7) + 1;
  return `学期第${weekNum}周`;
});

// 柱状图配置
const barChartOption = computed(() => {
  const filteredData = data.tableData.filter(item => {
    const className = item.className;
    const classNum = parseInt(className, 10);
    return classNum >= 701 && classNum <= 727;
  }).sort((a, b) => {
    return parseInt(a.className, 10) - parseInt(b.className, 10);
  });

  const classNames = filteredData.map(item => item.className);
  const totalPoints = filteredData.map(item => item.totalPoints);

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {type: 'shadow'},
      formatter: '{b}: {c} 积分'
    },
    grid: {left: '3%', right: '4%', bottom: '15%', containLabel: true},
    xAxis: {
      type: 'category',
      data: classNames,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      name: '积分',
      min: 0,
      axisLabel: {formatter: '{value}'}
    },
    series: [{
      name: '班级积分',
      type: 'bar',
      data: totalPoints,
      itemStyle: {
        color: (params) => {
          const maxPoint = Math.max(...totalPoints);
          const colorRatio = params.value / maxPoint;
          return colorRatio > 0.8 ? '#10b981' : colorRatio > 0.5 ? '#3b82f6' : '#60a5fa';
        },
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        fontSize: 12
      },
      barWidth: '60%'
    }]
  };
});
</script>

<style scoped>
.card {
  border: 1px solid #f0f0f0;
  overflow: hidden;
}

/* 关键修复：为图表容器设置明确的尺寸 */
.chart-container {
  width: 100%;
  min-height: 550px; /* 确保最小高度 */
}

.chart-wrapper {
  width: 100%;
  height: 500px; /* 明确设置高度 */
}

@media (max-width: 768px) {
  .mt-8 {
    margin-top: 40px;
  }

  .text-lg {
    font-size: 1rem;
  }

  .chart-wrapper {
    height: 300px; /* 小屏幕调整高度 */
  }
}
</style>
